<template>
  <div class="about">
    <h2>App1 - About Page</h2>
    
    <div class="info-section">
      <h3>从主应用接收的用户信息：</h3>
      <p>用户名：{{ userInfo?.name }}</p>
      <p>年龄：{{ userInfo?.age }}</p>
    </div>
    
    <div class="features">
      <h3>App1 功能特点：</h3>
      <ul>
        <li>✅ 支持独立运行和在qiankun微前端环境中运行</li>
        <li>✅ 接收主应用传递的用户信息</li>
        <li>✅ 能够向主应用发送更新请求</li>
        <li>✅ 支持与其他子应用共享数据</li>
      </ul>
    </div>
    
    <div class="communication-demo">
      <h3>实时数据同步演示：</h3>
      <p>当前时间：{{ currentTime }}</p>
      <p>如果在其他应用修改了用户信息，这里会自动更新</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 用户信息
const userInfo = ref<any>(null)
const currentTime = ref('')
let updateInterval: ReturnType<typeof setInterval> | null = null

// 获取全局状态
const getGlobalState = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState) {
    userInfo.value = globalState.userInfo
  }
}

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString()
}

// 设置全局状态变化监听
const setupGlobalStateListener = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState?.actions) {
    console.log('设置全局状态变化监听器')
    
    // 使用qiankun提供的onGlobalStateChange API监听状态变化
    return globalState.actions.onGlobalStateChange((state: any) => {
      console.log('全局状态变化:', state)
      if (state.userInfo && JSON.stringify(state.userInfo) !== JSON.stringify(userInfo.value)) {
        userInfo.value = { ...state.userInfo }
      }
    }, true) // true表示立即执行一次回调
  }
  return () => {}
}

onMounted(() => {
  console.log('AboutView组件挂载')
  
  // 获取初始状态
  getGlobalState()
  
  // 设置全局状态变化监听
  const cleanup = setupGlobalStateListener()
  
  // 设置定时器更新时间
  updateCurrentTime()
  updateInterval = setInterval(() => {
    updateCurrentTime()
  }, 1000)
  
  // 组件卸载时清理
  onUnmounted(() => {
    // 清理监听器
    cleanup()
    
    // 清理定时器
    if (updateInterval) {
      clearInterval(updateInterval)
    }
  })
})
</script>

<style scoped>
.about {
  padding: 20px;
}

h2 {
  color: #42b883;
  margin-bottom: 20px;
}

.info-section,
.features,
.communication-demo {
  background-color: #f8f8f8;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
}

h3 {
  margin-top: 0;
  color: #333;
}

ul {
  margin-top: 10px;
  padding-left: 20px;
}

li {
  margin-bottom: 5px;
}

.communication-demo {
  border-left: 4px solid #2196f3;
}
</style>